<template>
  <div id="dialogRoleExplain">
    <el-dialog
      class="pub-dialog"
      :title="title"
      :visible.sync="dialogData.isShow"
      width="800px"
      :before-close="labelHandleClose"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      fullscreen
      top="4px"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="版本号" prop="versionNumber">
            <el-input
              v-model.trim="ruleForm.versionNumber"
              placeholder="请输入版本号"
              maxlength="32"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              v-model="ruleForm.status"
              :active-value="true"
              :inactive-value="false"
              active-color="#1DC8A4"
              @change="changeRandom(ruleForm.status)"
            ></el-switch>
          </el-form-item>
          <!--富文本编辑器-->
          <el-form-item label="规则内容" prop="content">
            <quill-editor
              ref="text"
              v-model="ruleForm.content"
              class="myQuillEditor"
              :options="editorOption"
              @change="onEditorChange($event)"
              @blur="onEditorBlur($event)"
            ></quill-editor>
            <div class="limit">
              <span>{{ nowLength }}</span> / {{ maxLen }}
            </div>
            <div v-if="overText" class="red-note">
              文章内容不超过{{ maxLen }}字
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="saveLoading"
          @click="confirmLabel('ruleForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
    <dialogUploadImg
      :dialogData="dialogUpData"
      @setImgInfo="setImgInfo"
      v-if="dialogUpData.isShow"
    ></dialogUploadImg>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import '@assets/css/quill.snow.css'
import dialogUploadImg from '@component/readManagement/readMine/dialogUploadImg' // 上传图片组件
import {
  addIntegral,
  editIntegral,
  getDetail
} from '@/api/couponsIntegral/integralRole' //接口
export default {
  name: 'dialogRoleExplain',
  msg: '积分规则说明-新增/编辑弹窗',
  props: ['dialogData'],
  components: {
    quillEditor,
    dialogUploadImg
  },
  data() {
    return {
      isAdd: true,
      id: null,
      loading: false,
      saveLoading: false,
      title: '', //弹窗title
      ruleForm: {
        versionNumber: '', //版本号
        content: '', //文章内容
        textContent: '', //纯文本
        status: false // 状态 true/false
      },
      rules: {
        versionNumber: [{ required: true, message: '版本号不能为空' }],
        content: {
          required: true
        }
      },
      nowLength: 0,
      editorIndex: 0, //编辑器光标位置
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ header: 1 }, { header: 2 }],
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ color: [] }, { background: [] }],
              [{ align: [] }],
              ['image']
            ],
            handlers: {
              image: (value) => {
                if (value) {
                  // 在这里编写图片按钮点击操作
                  let quill = this.$refs.text.quill
                  this.editorIndex = quill.getSelection()
                    ? quill.getSelection().index
                    : 0
                  this.dialogUpData.isShow = true
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          },
          clipboard: {
            matchers: [[Node.ELEMENT_NODE, this.HandleCustomMatcher]]
          }
        },
        placeholder: '请输入正文'
      },
      clearStyle: false, //是否执行清除样式，true-执行；false-不执行
      dialogUpData: {
        isShow: false
      },
      maxLen: 5000,
      overText: false, //富文本字数是否超过5000
      submitCon: '' //提交内容
    }
  },
  mounted() {
    if (this.dialogData.id) {
      //编辑
      this.isAdd = false
      this.id = this.dialogData.id
      this.getFormDetail()
      this.title = '编辑规则'
    } else {
      //新增
      this.clearStyle = true
      this.title = '新增规则'
    }
  },
  methods: {
    /*文字、图片等，从别处复制而来，清除自带样式，转为纯文本*/
    HandleCustomMatcher(node, Delta) {
      if (this.clearStyle) {
        let ops = []
        Delta.ops.forEach((op) => {
          if (op.insert && typeof op.insert === 'string') {
            ops.push({
              insert: op.insert
            })
          }
        })
        Delta.ops = ops
        return Delta
      } else {
        return Delta
      }
    },
    //获取表单详情
    getFormDetail() {
      let _this = this
      getDetail(
        this.id,
        (response) => {
          this.ruleForm = {
            versionNumber: response.versionNumber, //版本号
            content: response.content, //文章内容
            status: response.status // 状态 true/false
          }
          this.$nextTick(() => {
            this.clearStyle = true
          })
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    //计算富文本编辑器，当前输入的字数
    onEditorChange(event) {
      let value = event.quill.getText()
      this.ruleForm.textContent = value.slice(0, -1)
      if (this.ruleForm.content === '') {
        this.nowLength = 0
      } else {
        this.nowLength = value.length - 1
      }
      this.overText = this.nowLength > this.maxLen ? true : false
      if (this.overText) {
        this.$message.warning(`文章内容不超过${this.maxLen}字`)
      }
    },
    onEditorBlur(event) {},
    //图片插入富文本编辑器
    setImgInfo(ary) {
      // 获取富文本组件实例
      let quill = this.$refs.text.quill
      if (ary) {
        // 插入图片，res为服务器返回的图片链接地址
        for (let item of ary) {
          quill.insertEmbed(this.editorIndex++, 'image', item.url)
        }
        // 调整光标到最后
        quill.setSelection(this.editorIndex)
      }
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
      this.dialogData.id = ''
    },
    /* 改变状态 */
    changeRandom(status) {
      if (status === true) {
        this.$message.warning('该规则开启后，之前开启的规则会自动关闭！')
      }
    },
    //富文本内容替换
    replaceCon() {
      let content = this.$refs.text.value
      /* let content = value.replace(/<(?!\/?IMG|\/?P)[^<>]*>/gi, '')
      content = content.replace(/<P.*?>/gi, '<P>')*/
      if (content.trim().length === 0) {
        this.$message.warning('文章内容不能为空！')
        return ''
      }
      let time = new Date().getTime()
      content =
        `<html><head><link href='https://blob.dapengjiaoyu.com/operate/css/quill-snow.css?${time}' rel='stylesheet' type='text/css'><meta name='viewport' content='width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no'/></head><body><div class='ql-snow'><div class='ql-editor ql-container'>` +
        content +
        '</div></div></body></html>'
      return content
    },
    beforSubmit() {
      //文字超过最大限制
      if (this.overText) {
        this.$message.warning(`文章内容不超过${this.maxLen}字`)
        return false
      }
      this.submitCon = this.replaceCon()
      //没有文章内容
      if (!this.submitCon) {
        return false
      }
      return true
    },
    /* 提交 */
    async confirmLabel(formName) {
      let flog = this.beforSubmit()
      if (!flog) return
      this.loading = true
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let obj = { ...this.ruleForm }
          obj.content = this.submitCon
          /* console.log("obj=")
          console.log(obj)*/
          if (this.isAdd) {
            addIntegral(
              obj,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning('保存失败，' + response.message)
              }
            )
          } else {
            editIntegral(
              obj,
              this.id,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning('保存失败，' + response.message)
              }
            )
          }
        } else {
          this.loading = false
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" rel="stylesheet/less">
#dialogRoleExplain {
  @import url('~@common/style/textarea.less');
  .pub-dialog {
    .el-dialog__body {
      padding-top: 5px !important;
    }
  }
  .el-form-item {
    margin-bottom: 8px !important;
  }
  .el-dialog__headerbtn .el-dialog__close {
    color: #000;
  }
  .ql-toolbar.ql-snow {
    padding: 0;
  }
  .red-note {
    position: absolute;
    bottom: -23px;
    padding-left: 10px;
    color: #f00;
  }
  .el-form-item__error {
    padding: 0;
  }
  .el-dialog__wrapper {
    /* z-index: 3000 !important;*/
  }
  .quill-editor {
    .ql-container {
      height: calc(100vh - 264px);
      .ql-editor {
        height: calc(~'100% - 30px');
      }
    }
  }
  .limit {
    height: 30px;
    line-height: 30px;
    text-align: right;
    margin: -30px 0 10px;
    padding-right: 10px;
    span {
      color: #f00;
    }
  }
  .el-button.pc-preview {
    padding: 5px 0 !important;
    a {
      color: #fff;
      padding: 5px 35px;
      &:hover {
        color: #fff;
      }
    }
  }
}
</style>
